package intranet.server;

/**
 * @author Baptiste RENDU
 */

import intranet.client.ConnexionService;
import intranet.client.Session;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.http.HttpSession;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class ConnexionServiceImpl extends RemoteServiceServlet implements
		ConnexionService {
	
	
	@Override
	/**
	 * retourne une Session contenant des informations sur l'utilisateur
	 * @param les elements permettant de l'identifier
	 */
	public Session getSession(String login, String password){
		// Verify that the input is valid.
		Session session = new Session();
		boolean valid=false;
		if(login.isEmpty()||password.isEmpty())
		{
			return null;
		}
			try {
				Class.forName("org.postgresql.Driver");
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				System.out.println("erreur1");
				e.printStackTrace();	
			}
		
		Connection connect=null;
		try {
			connect = DriverManager.getConnection("jdbc:postgresql:intranet-grpc","postgres", "grpc");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("erreur2");
			e.printStackTrace();	
		}
		
		Statement state=null;
		try {
			state = connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("erreur3");
			e.printStackTrace();
		}
		
		ResultSet result=null;
		try {
			result = state.executeQuery("select * from teacher where teacher_login='" + login + "'");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("erreur4");
			e.printStackTrace();
		}
		if(result!=null)
		{
			try {
				result.last();
				int nb=result.getRow();
				result.first();
				if (nb == 1) {
					MessageDigest m= MessageDigest.getInstance("MD5");
						m.reset();
						m.update((password + result
								.getString("teacher_grainofsalt")).getBytes());
						byte[] digest = m.digest();
						BigInteger bigInt = new BigInteger(1, digest);
						String encryptedPassword = bigInt.toString(16);

						while (encryptedPassword.length() < 32) {
							encryptedPassword = "0" + encryptedPassword;
						}
						if (encryptedPassword.equals(result.getString("teacher_password"))) 
						{
							HttpSession httpSession = 
								getThreadLocalRequest().getSession();
							httpSession.setAttribute("teacher_login",result.getString("teacher_login"));
							httpSession.setAttribute("teacher_status",result.getString("teacher_status"));
							httpSession.setMaxInactiveInterval(1800);
								                if(httpSession != null)
								                {
								                		valid=true;
								                        session.add("sessionId",httpSession.getId());
								                        session.add("teacher_login",result.getString("teacher_login"));
								                        session.add("teacher_status",result.getString("teacher_status"));
								                }
						}
						
						 connect.close();
						 
				}
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				System.out.println("erreur5");
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				System.out.println("erreur6");
				e.printStackTrace();
			}
		}
		if(valid)
			return session;
		else
			return null;
	}
	/**
	 * test si une session courante existe
	 */
	@Override
	public Session validate() {
		Session s = new Session();
		HttpSession httpSession = getThreadLocalRequest().getSession(false);
		if (httpSession != null) {
			s.add("sessionId",httpSession.getId());
			s.add("teacher_login",(String)httpSession.getAttribute("teacher_login"));
			s.add("teacher_status",(String)httpSession.getAttribute("teacher_status"));
		}
		return s;
	}
	/**
	 * détruit la session courante sur le serveur
	 * @return retourne true si la session a été détruite, false sinon
	 */
	@Override
	public boolean invalidate() {
		// TODO Auto-generated method stub
		HttpSession httpSession = getThreadLocalRequest().getSession(false);
		if (httpSession != null) {
			httpSession.invalidate();
			return true;
		}
		return false;
	}
}